package com.zw.cloud.mybatis.plus.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zw.cloud.common.utils.DingTalkUtils;
import com.zw.cloud.mybatis.plus.entity.Fc;
import com.zw.cloud.mybatis.plus.entity.dto.FcDTO;
import com.zw.cloud.mybatis.plus.entity.dto.FcResultDTO;
import com.zw.cloud.mybatis.plus.mapper.FcMapper;
import com.zw.cloud.mybatis.plus.service.api.IFcService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 体彩 服务实现类
 * </p>
 *
 * @author zw
 * @since 2022-08-03
 */
@Service
public class FcServiceImpl extends ServiceImpl<FcMapper, Fc> implements IFcService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public List<Fc> queryFcListFromRemote(int pageNo) {
        String url = "http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount=&issueStart=&issueEnd=&dayStart=&dayEnd=&pageNo="+ pageNo +"&pageSize=30&week=&systemType=PC";
        String result = restTemplate.getForObject(url, String.class);
        FcResultDTO fcResultDTO = JSON.parseObject(result, FcResultDTO.class);
        if (Objects.isNull(fcResultDTO) || CollectionUtils.isEmpty(fcResultDTO.getResult())) {
            return Collections.emptyList();
        }
        List<Fc> fcList = new ArrayList<>();
        List<FcResultDTO.FcDTO> fcDTOList = fcResultDTO.getResult();
        for (FcResultDTO.FcDTO fcDTO : fcDTOList) {
            Fc.FcBuilder builder = Fc.builder();
            String[] split = fcDTO.getRed().split(",");
            builder.id(Integer.parseInt(fcDTO.getCode())).one(Integer.parseInt(split[0]))
                    .two(Integer.parseInt(split[1])).three(Integer.parseInt(split[2]))
                    .four(Integer.parseInt(split[3])).five(Integer.parseInt(split[4]))
                    .six(Integer.parseInt(split[5])).seven(Integer.parseInt(fcDTO.getBlue()));
            fcList.add(builder.build());
        }
        return fcList;
    }

    @Override
    public List<FcDTO> queryFcList(Integer count) {
        LambdaQueryWrapper<Fc> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Fc::getId).last("limit " + count);
        List<Fc> list = list(queryWrapper);
        return list.stream().map(fc -> {
            FcDTO dto = new FcDTO();
            dto.setOne(fc.getOne());
            dto.setTwo(fc.getTwo());
            dto.setThree(fc.getThree());
            dto.setFour(fc.getFour());
            dto.setFive(fc.getFive());
            dto.setSix(fc.getSix());
            dto.setSeven(fc.getSeven());
            dto.setCount(fc.getOne() + fc.getTwo() + fc.getThree() + fc.getFour() + fc.getFive());
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> queryList(Integer count) {
        LambdaQueryWrapper<Fc> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Fc::getId).last("limit " + count);
        List<Fc> fcList = list(queryWrapper);
        List<Integer> exitList = new ArrayList<>(60);
        List<Integer> blueList = new ArrayList<>();
        fcList.forEach(fc -> {
            exitList.add(fc.getOne());
            exitList.add(fc.getTwo());
            exitList.add(fc.getThree());
            exitList.add(fc.getFour());
            exitList.add(fc.getFive());
            exitList.add(fc.getSix());
            blueList.add(fc.getSeven());
        });
        return randomNum(fcList);
    }

    @Override
    public void sendFcMsg(Integer count) {
        List<Fc> fcList = queryFcListFromRemote(1);
        if (CollectionUtils.isEmpty(fcList)) {
            return;
        }
        fcList = fcList.stream().sorted(Comparator.comparing(Fc::getId).reversed()).collect(Collectors.toList());
        fcList = fcList.subList(0,count);
        randomNum(fcList);
    }

    private Map<String,Object> randomNum(List<Fc> fcList) {
        List<Integer> exitList = new ArrayList<>(60);
        List<Integer> blueList = new ArrayList<>();
        fcList.forEach(fc -> {
            exitList.add(fc.getOne());
            exitList.add(fc.getTwo());
            exitList.add(fc.getThree());
            exitList.add(fc.getFour());
            exitList.add(fc.getFive());
            exitList.add(fc.getSix());
            blueList.add(fc.getSeven());
        });
        Map<String,Object> result = new HashMap<>();
        Set<Integer> resultSet = new HashSet<>(8);
        while (resultSet.size() < 6) {
            Random random = new Random();
            int index = random.nextInt(exitList.size());
            resultSet.add(exitList.get(index));
        }
        List<Integer> redList = resultSet.stream().sorted(Comparator.comparingInt(s -> s)).collect(Collectors.toList());
        result.put("redList", redList);
        result.put("blueList",blueList);
        fcList.sort(Comparator.comparing(Fc::getId));
        StringBuilder msg = new StringBuilder("FC最近开奖: \n\n");
        for (Fc fc : fcList) {
            msg.append(fc.getId()).append("  ")
                    .append("<font color=#FF0000>")
                    .append(String.format("%02d",fc.getOne())).append(" ")
                    .append(String.format("%02d",fc.getTwo())).append(" ")
                    .append(String.format("%02d",fc.getThree())).append(" ")
                    .append(String.format("%02d",fc.getFour())).append(" ")
                    .append(String.format("%02d",fc.getFive())).append(" ")
                    .append(String.format("%02d",fc.getSix()))
                    .append("</font>").append(" ")
                    .append("<font color=#0000FF>")
                    .append(String.format("%02d",fc.getSeven()))
                    .append("</font>").append(" ")
                    .append("\n\n");
        }
        msg.append("<font color=#FF0000>").append(redList.stream().map(String::valueOf).collect(Collectors.joining(" ")))
                .append("</font>").append("  ")
                .append("<font color=#0000FF>").append(new Random().nextInt(15) + 1)
                .append("</font>")
                .append("\n\n");

        DingTalkUtils.sendDingTalkMsgWithSign("FC",msg.toString());
        return result;
    }
}
